<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { getUserByUsername } from '@/services/userService'
import { getLandslideFeatures } from '@/services/landslideService'
import { User } from '@element-plus/icons-vue'

// 获取用户状态管理和路由
const userStore = useUserStore()
const router = useRouter()

// 用户详细信息
const userDetail = ref<any>(null)
const loading = ref(false)

// 滑坡数据
const landslideFeatures = ref<any[]>([])
const landslideLoading = ref(false)
const highRiskCount = ref(0)

// 动画效果相关
const welcomeClass = ref('')

// 当前时间
const currentTime = ref(new Date())

// 更新时间的定时器
let timer: number | null = null

// 系统功能列表
const systemFeatures = [
  {
    title: '地图查看',
    icon: 'MapLocation',
    description: '查看巴中市区域内的滑坡风险点分布情况，支持地图缩放、平移等操作。',
    route: '/map/view',
    color: '#4CAF50',
  },
  {
    title: '统计分析',
    icon: 'DataAnalysis',
    description: '查看滑坡风险统计数据，包括风险等级分布、时间趋势分析等。',
    route: '/statistics',
    color: '#2196F3',
  },
  {
    title: '预警信息',
    icon: 'Warning',
    description: '查看最新的滑坡风险预警信息，及时了解高风险区域。',
    route: '/map/view',
    color: '#FF9800',
  },
]

// 系统公告
const announcements = [
  {
    title: '系统上线通知',
    date: '2023-04-28',
    content: '巴中市滑坡风险预警系统正式上线，为全市提供滑坡风险预警服务。',
  },
  {
    title: '功能更新公告',
    date: '2023-04-29',
    content: '系统新增统计分析功能，支持多维度数据分析和可视化展示。',
  },
  {
    title: '安全预警提示',
    date: '2023-04-30',
    content: '近期降雨较多，请密切关注系统预警信息，做好防范措施。',
  },
]

// 计算当前季节
const currentSeason = computed(() => {
  const month = currentTime.value.getMonth() + 1
  if (month >= 3 && month <= 5) return '春季'
  if (month >= 6 && month <= 8) return '夏季'
  if (month >= 9 && month <= 11) return '秋季'
  return '冬季'
})

// 计算当前天气风险等级（基于高风险滑坡点数量）
const weatherRiskLevel = computed(() => {
  // 基于高风险滑坡点数量确定当前风险等级
  if (highRiskCount.value >= 10) return { level: '高风险', type: 'danger' }
  if (highRiskCount.value >= 5) return { level: '中风险', type: 'warning' }
  return { level: '低风险', type: 'success' }
})

// 计算各风险等级的数量
const riskLevelCounts = computed(() => {
  const counts = {
    low: 0,
    medium: 0,
    high: 0,
    extreme: 0,
  }

  landslideFeatures.value.forEach((feature) => {
    if (feature.attributes) {
      const riskLevel = feature.attributes.riskLevel
      if (riskLevel === '低风险') counts.low++
      else if (riskLevel === '中风险') counts.medium++
      else if (riskLevel === '高风险') counts.high++
      else if (riskLevel === '极高风险') counts.extreme++
    }
  })

  return counts
})

/**
 * 组件挂载时的动画效果和初始化
 */
onMounted(async () => {
  // 添加进入动画类
  setTimeout(() => {
    welcomeClass.value = 'welcome-show'
  }, 100)

  // 更新时间
  updateTime()
  // 设置定时器，每秒更新一次时间
  timer = window.setInterval(updateTime, 1000)

  // 加载用户详细信息
  if (userStore.userInfo?.username) {
    loading.value = true
    try {
      const user = await getUserByUsername(userStore.userInfo.username)
      if (user) {
        userDetail.value = user
      }
    } catch (error) {
      console.error('获取用户详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 加载滑坡要素数据
  landslideLoading.value = true
  try {
    // 获取真实数据
    const arcgisFeatures = await getLandslideFeatures()

    // 将ArcGIS对象转换为普通JavaScript对象
    const plainFeatures = arcgisFeatures
      ? arcgisFeatures.map((feature) => {
          // 提取需要的属性
          return {
            attributes: feature.attributes
              ? {
                  ...feature.attributes,
                  riskLevel: feature.attributes.riskLevel || '未知',
                  name: feature.attributes.name || '',
                  Address: feature.attributes.Address || '',
                  occuredTime: feature.attributes.occuredTime || '',
                  Description: feature.attributes.Description || '',
                }
              : {
                  riskLevel: '未知',
                  name: '',
                  Address: '',
                  occuredTime: '',
                  Description: '',
                },
            // 安全地提取几何信息
            geometry:
              feature.geometry && feature.geometry.type === 'point'
                ? {
                    // 对于Point类型，我们可以安全地访问x和y属性
                    longitude: feature.geometry.longitude || feature.geometry.x,
                    latitude: feature.geometry.latitude || feature.geometry.y,
                  }
                : null,
          }
        })
      : []

    // 将普通对象存储在ref变量中
    landslideFeatures.value = plainFeatures

    // 计算高风险滑坡点数量
    highRiskCount.value = landslideFeatures.value.filter(
      (feature) =>
        feature.attributes &&
        (feature.attributes.riskLevel === '高风险' || feature.attributes.riskLevel === '极高风险'),
    ).length
  } catch (error) {
    console.error('获取滑坡要素数据失败:', error)
    // 出错时清空数据
    landslideFeatures.value = []
    highRiskCount.value = 0
  } finally {
    landslideLoading.value = false
  }
})

/**
 * 组件卸载时清除定时器
 */
onMounted(() => {
  return () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }
})

/**
 * 导航到指定路由
 */
function navigateTo(route: string) {
  router.push(route)
}

/**
 * 更新当前时间
 */
function updateTime() {
  currentTime.value = new Date()
}

/**
 * 格式化时间为 HH:MM:SS
 */
function formatTime(date: Date): string {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

/**
 * 格式化日期为 YYYY年MM月DD日 星期X
 */
function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekdays = ['日', '一', '二', '三', '四', '五', '六']
  const weekday = weekdays[date.getDay()]
  return `${year}年${month}月${day}日 星期${weekday}`
}
</script>

<template>
  <div class="user-welcome" :class="welcomeClass">
    <div class="welcome-header">
      <div class="header-left">
        <h1>欢迎使用巴中市滑坡风险预警系统</h1>
        <p class="subtitle">为巴中市提供专业的滑坡风险预警服务</p>
      </div>
      <div class="time-display">
        <div class="time">{{ formatTime(currentTime) }}</div>
        <div class="date">{{ formatDate(currentTime) }}</div>
        <div class="season">当前季节：{{ currentSeason }}</div>
      </div>
    </div>

    <div class="welcome-content">
      <!-- 用户信息卡片 -->
      <el-card class="welcome-card user-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>用户信息</span>
          </div>
        </template>
        <div class="card-content">
          <div class="user-avatar">
            <el-avatar :size="80" :icon="User" />
            <h3>{{ userStore.userInfo?.username }}</h3>
          </div>
          <div class="user-info">
            <p><strong>用户名：</strong>{{ userStore.userInfo?.username }}</p>
            <p><strong>姓名：</strong>{{ userDetail?.name || '未设置' }}</p>
            <p><strong>部门：</strong>{{ userDetail?.department || '未设置' }}</p>
            <p><strong>角色：</strong>普通用户</p>
            <p><strong>登录状态：</strong><el-tag type="success">已登录</el-tag></p>
            <p><strong>上次登录：</strong>{{ userDetail?.lastLogin || '首次登录' }}</p>
          </div>
        </div>
      </el-card>

      <!-- 系统概览卡片 -->
      <el-card class="welcome-card overview-card" v-loading="landslideLoading">
        <template #header>
          <div class="card-header">
            <el-icon><DataBoard /></el-icon>
            <span>系统概览</span>
          </div>
        </template>
        <div class="card-content">
          <div class="overview-item">
            <div class="overview-icon" style="background-color: #4caf50">
              <el-icon><MapLocation /></el-icon>
            </div>
            <div class="overview-info">
              <h3>滑坡风险点</h3>
              <p>
                系统当前共记录了<strong>{{ landslideFeatures.length }}</strong
                >个滑坡风险点
              </p>
            </div>
          </div>
          <div class="overview-item">
            <div class="overview-icon" style="background-color: #ff9800">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="overview-info">
              <h3>风险预警</h3>
              <p>
                当前有<strong>{{ highRiskCount }}</strong
                >个高风险预警点需要关注
              </p>
            </div>
          </div>
          <div class="overview-item">
            <div class="overview-icon" style="background-color: #2196f3">
              <el-icon><Cloudy /></el-icon>
            </div>
            <div class="overview-info">
              <h3>天气风险</h3>
              <p>
                当前天气风险等级：<el-tag :type="weatherRiskLevel.type">{{
                  weatherRiskLevel.level
                }}</el-tag>
              </p>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 风险等级分布卡片 -->
      <el-card class="welcome-card risk-card" v-loading="landslideLoading">
        <template #header>
          <div class="card-header">
            <el-icon><PieChart /></el-icon>
            <span>风险等级分布</span>
          </div>
        </template>
        <div class="card-content">
          <div class="risk-distribution">
            <div class="risk-item">
              <div class="risk-level" style="background-color: #4caf50">低风险</div>
              <div class="risk-bar-container">
                <div
                  class="risk-bar"
                  :style="{
                    backgroundColor: '#4CAF50',
                    width:
                      (riskLevelCounts.low / Math.max(landslideFeatures.length, 1)) * 100 + '%',
                  }"
                ></div>
              </div>
              <div class="risk-count">{{ riskLevelCounts.low }}</div>
            </div>
            <div class="risk-item">
              <div class="risk-level" style="background-color: #ffeb3b">中风险</div>
              <div class="risk-bar-container">
                <div
                  class="risk-bar"
                  :style="{
                    backgroundColor: '#FFEB3B',
                    width:
                      (riskLevelCounts.medium / Math.max(landslideFeatures.length, 1)) * 100 + '%',
                  }"
                ></div>
              </div>
              <div class="risk-count">{{ riskLevelCounts.medium }}</div>
            </div>
            <div class="risk-item">
              <div class="risk-level" style="background-color: #ff9800">高风险</div>
              <div class="risk-bar-container">
                <div
                  class="risk-bar"
                  :style="{
                    backgroundColor: '#FF9800',
                    width:
                      (riskLevelCounts.high / Math.max(landslideFeatures.length, 1)) * 100 + '%',
                  }"
                ></div>
              </div>
              <div class="risk-count">{{ riskLevelCounts.high }}</div>
            </div>
            <div class="risk-item">
              <div class="risk-level" style="background-color: #f44336">极高风险</div>
              <div class="risk-bar-container">
                <div
                  class="risk-bar"
                  :style="{
                    backgroundColor: '#F44336',
                    width:
                      (riskLevelCounts.extreme / Math.max(landslideFeatures.length, 1)) * 100 + '%',
                  }"
                ></div>
              </div>
              <div class="risk-count">{{ riskLevelCounts.extreme }}</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 系统功能卡片 -->
      <el-card class="welcome-card features-card">
        <template #header>
          <div class="card-header">
            <el-icon><Operation /></el-icon>
            <span>系统功能</span>
          </div>
        </template>
        <div class="card-content">
          <div class="features-list">
            <div
              v-for="feature in systemFeatures"
              :key="feature.title"
              class="feature-item"
              @click="navigateTo(feature.route)"
            >
              <div class="feature-icon" :style="{ backgroundColor: feature.color }">
                <el-icon><component :is="feature.icon" /></el-icon>
              </div>
              <div class="feature-info">
                <h3>{{ feature.title }}</h3>
                <p>{{ feature.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 系统公告卡片 -->
      <el-card class="welcome-card announcement-card">
        <template #header>
          <div class="card-header">
            <el-icon><Bell /></el-icon>
            <span>系统公告</span>
          </div>
        </template>
        <div class="card-content">
          <div class="announcement-list">
            <div
              v-for="(announcement, index) in announcements"
              :key="index"
              class="announcement-item"
            >
              <div class="announcement-header">
                <h3>{{ announcement.title }}</h3>
                <span class="announcement-date">{{ announcement.date }}</span>
              </div>
              <p>{{ announcement.content }}</p>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 使用指南卡片 -->
      <el-card class="welcome-card guide-card">
        <template #header>
          <div class="card-header">
            <el-icon><Guide /></el-icon>
            <span>使用指南</span>
          </div>
        </template>
        <div class="card-content">
          <div class="guide-steps">
            <div class="guide-step">
              <div class="step-number">1</div>
              <div class="step-content">
                <h3>查看地图</h3>
                <p>在地图页面查看滑坡风险点分布情况，可以进行缩放、平移等操作。</p>
              </div>
            </div>
            <div class="guide-step">
              <div class="step-number">2</div>
              <div class="step-content">
                <h3>筛选数据</h3>
                <p>使用筛选功能，按风险等级、时间等条件筛选滑坡风险点。</p>
              </div>
            </div>
            <div class="guide-step">
              <div class="step-number">3</div>
              <div class="step-content">
                <h3>查看统计</h3>
                <p>在统计分析页面查看滑坡风险数据的统计图表和趋势分析。</p>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 联系我们卡片 -->
      <el-card class="welcome-card contact-card">
        <template #header>
          <div class="card-header">
            <el-icon><Phone /></el-icon>
            <span>联系我们</span>
          </div>
        </template>
        <div class="card-content">
          <p><strong>地址：</strong>四川省巴中市巴州区江北大道</p>
          <p><strong>电话：</strong>0827-12345678</p>
          <p><strong>邮箱：</strong>support@bazhong-landslide.gov.cn</p>
          <p><strong>工作时间：</strong>周一至周五 9:00-17:30</p>
          <p class="emergency-contact">
            <strong>紧急联系：</strong>如遇紧急情况，请拨打应急电话：0827-87654321
          </p>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-welcome {
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s ease;
  background: linear-gradient(135deg, #ffecb3 0%, #ffcc80 100%);
  padding: 20px;
  min-height: 100%;

  &.welcome-show {
    opacity: 1;
    transform: translateY(0);
  }
}

.welcome-header {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .header-left {
    h1 {
      font-size: 28px;
      color: #b71c1c;
      margin: 0 0 10px 0;
      text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
    }

    .subtitle {
      font-size: 16px;
      color: #e65100;
      margin: 0;
    }
  }

  .time-display {
    text-align: right;
    background: rgba(255, 255, 255, 0.7);
    padding: 10px 15px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .time {
      font-size: 32px;
      font-weight: bold;
      color: #e65100;
    }

    .date {
      font-size: 16px;
      color: #ff9800;
      margin: 5px 0;
    }

    .season {
      font-size: 14px;
      color: #7f4f24;
    }
  }
}

.welcome-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.welcome-card {
  height: 100%;
  transition: all 0.3s;
  background: rgba(255, 248, 225, 0.9);
  border: 1px solid #ffcc80;
  border-radius: 8px;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 18px;
    font-weight: bold;
    background: linear-gradient(to right, #ffb74d, #ff9800);
    color: #7f4f24;
    padding: 15px;
  }

  .card-content {
    padding: 20px;

    p {
      margin: 10px 0;
      color: #5d4037;
    }
  }
}

// 用户信息卡片
.user-card {
  .card-content {
    display: flex;
    flex-direction: column;

    .user-avatar {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 10px 0 0 0;
        color: #e65100;
      }
    }

    .user-info {
      p {
        margin: 8px 0;

        strong {
          color: #7f4f24;
          display: inline-block;
          width: 80px;
        }
      }
    }
  }
}

// 系统概览卡片
.overview-card {
  .overview-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px;
    background: rgba(255, 255, 255, 0.5);
    border-radius: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .overview-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 15px;

      .el-icon {
        font-size: 24px;
        color: white;
      }
    }

    .overview-info {
      flex: 1;

      h3 {
        margin: 0 0 5px 0;
        color: #7f4f24;
      }

      p {
        margin: 0;

        strong {
          color: #e65100;
          font-size: 18px;
        }
      }
    }
  }
}

// 系统功能卡片
.features-card {
  .features-list {
    .feature-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      padding: 15px;
      background: rgba(255, 255, 255, 0.5);
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;

      &:last-child {
        margin-bottom: 0;
      }

      &:hover {
        background: rgba(255, 255, 255, 0.8);
        transform: translateX(5px);
      }

      .feature-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 15px;

        .el-icon {
          font-size: 30px;
          color: white;
        }
      }

      .feature-info {
        flex: 1;

        h3 {
          margin: 0 0 8px 0;
          color: #7f4f24;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #5d4037;
        }
      }
    }
  }
}

// 系统公告卡片
.announcement-card {
  .announcement-list {
    .announcement-item {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px dashed #ffcc80;

      &:last-child {
        margin-bottom: 0;
        padding-bottom: 0;
        border-bottom: none;
      }

      .announcement-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        h3 {
          margin: 0;
          color: #e65100;
          font-size: 16px;
        }

        .announcement-date {
          font-size: 12px;
          color: #7f4f24;
        }
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }
}

// 使用指南卡片
.guide-card {
  .guide-steps {
    .guide-step {
      display: flex;
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .step-number {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #e65100;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: bold;
        margin-right: 15px;
        flex-shrink: 0;
      }

      .step-content {
        h3 {
          margin: 0 0 5px 0;
          color: #7f4f24;
        }

        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }
  }
}

// 联系我们卡片
.contact-card {
  .card-content {
    p {
      margin: 12px 0;

      strong {
        color: #7f4f24;
      }
    }

    .emergency-contact {
      margin-top: 20px;
      padding: 10px;
      background-color: rgba(255, 152, 0, 0.2);
      border-left: 3px solid #ff9800;
      border-radius: 4px;

      strong {
        color: #e65100;
      }
    }
  }
}

// 风险等级分布卡片
.risk-card {
  .risk-distribution {
    .risk-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .risk-level {
        width: 80px;
        padding: 4px 8px;
        text-align: center;
        border-radius: 4px;
        color: white;
        font-size: 14px;
        font-weight: bold;
        margin-right: 10px;
      }

      .risk-bar-container {
        flex: 1;
        height: 20px;
        background-color: rgba(0, 0, 0, 0.05);
        border-radius: 10px;
        overflow: hidden;
        margin-right: 10px;

        .risk-bar {
          height: 100%;
          border-radius: 10px;
          transition: width 0.5s ease;
        }
      }

      .risk-count {
        width: 40px;
        text-align: right;
        font-weight: bold;
        color: #7f4f24;
      }
    }
  }
}
</style>
